from django.shortcuts import render, redirect
import random
from datetime import datetime
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01.utils.form import BootStrapModelForm
from app01 import models
from app01.utils.pagination import Pagination


class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        fields = '__all__'
        exclude = ['oid', 'admin']


def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')
    page_obj = Pagination(request, queryset)

    form = OrderModelForm()
    context = {
        'form': form,
        'queryset': page_obj.page_queryset,
        'page_str': page_obj.html()
    }
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_add(request):
    """创建订单 (ajax)"""
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 将订单号自动生成, 不需要用户输入
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))

        # 设置管理员id (当前登陆的管理员的id)
        form.instance.admin_id = request.session['info']['id']

        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, 'error': form.errors})


def order_delete(request):
    """删除订单"""
    uid = request.GET.get('uid')
    exists = models.Order.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, 'error': '数据不存在'})
    models.Order.objects.filter(id=uid).delete()

    return JsonResponse({"status": True})


def order_detail(request):
    """根据ID获取订单详细"""
    # 方式1
    """
    uid = request.GET.get('uid')
    row_obj = models.Order.objects.filter(id=uid).first()
    if not row_obj:
        return JsonResponse({"status": False, 'error': '数据不存在'})
    # 数据库中的对象 row_obj
    result = {
        "status": True,
        "data": {
            'title': row_obj.title,
            'price': row_obj.price,
            'status': row_obj.status
        }
    }
    return JsonResponse(result)
    """
    # 方式2
    uid = request.GET.get('uid')
    # .values('ids') 生成字典
    row_dict = models.Order.objects.filter(id=uid).values('title', 'price', 'status').first()
    if not row_dict:
        return JsonResponse({"status": False, 'error': '数据不存在'})
    # 数据库中的对象 row_obj
    result = {
        "status": True,
        "data": row_dict
    }
    return JsonResponse(result)


@csrf_exempt
def order_edit(request):
    """编辑"""
    uid = request.GET.get('uid')
    row_obj = models.Order.objects.filter(id=uid).first()
    if not row_obj:
        return JsonResponse({"status": False, 'tips': '数据不存在, 请重试'})
    form = OrderModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, 'error': form.errors})

